//
//  UITabBar+WLTabbarBadge.m
//  WanLian
//
//  Created by muzhuang on 2018/10/23.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "UITabBar+WLTabbarBadge.h"

#define TabbarItemNums 3    //tabbar的数量

@implementation UITabBar (WLTabbarBadge)

- (void)showBadgeOnItemIndex:(NSInteger)index{
    
    //移除之前的小红点
    [self removeBadgeOnItemIndex:index];
    
    //新建小红点
    UIView *badgeView = [[UIView alloc]init];
    badgeView.tag = 888 + index;
    badgeView.layer.cornerRadius = 3;
    badgeView.backgroundColor = wlRedColor;
    CGRect tabFrame = self.frame;
    
    //确定小红点的位置
    float percentX ;
    CGFloat x ;
    CGFloat y ;
//    if (index == 2) {
//        percentX = (index +0.55) / TabbarItemNums;
//        x = ceilf(percentX * tabFrame.size.width);
//        y = ceilf(-0.15 * tabFrame.size.height);
//    }
//    else
    {
        percentX = (index +0.55) / TabbarItemNums;
        x = ceilf(percentX * tabFrame.size.width);
        y = ceilf(0.1 * tabFrame.size.height);
    }
    badgeView.frame = CGRectMake(x, y, 6, 6);
    [self addSubview:badgeView];
}

- (void)hideBadgeOnItemIndex:(NSInteger)index
{
    //移除小红点
    [self removeBadgeOnItemIndex:index];
}

- (void)removeBadgeOnItemIndex:(NSInteger)index
{
    //按照tag值进行移除
    for (UIView *subView in self.subviews)
    {
        if (subView.tag == 888+index)
        {
            [subView removeFromSuperview];
        }
    }
}

- (BOOL)isShowBadge:(NSInteger)index
{
    BOOL isBadge = NO;
    for (UIView *subView in self.subviews)
    {
        if (subView.tag == 888+index)
        {
            isBadge = YES;
            break;
        }
    }
    return isBadge;
}

@end
